home *** CD-ROM | disk | FTP | other *** search
/ PC World 2007 September / PCWorld_2007-09_cd.bin / komunikace / firefox / Firefox Setup 2.0.0.6.exe / nonlocalized / components / nsHelperAppDlg.js < prev    next >
Encoding:
JavaScript  |  2007-07-25  |  38.5 KB  |  991 lines

  1. /*
  2. //@line 42 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  3. */
  4.  
  5. /* This file implements the nsIHelperAppLauncherDialog interface.
  6.  *
  7.  * The implementation consists of a JavaScript "class" named nsUnknownContentTypeDialog,
  8.  * comprised of:
  9.  *   - a JS constructor function
  10.  *   - a prototype providing all the interface methods and implementation stuff
  11.  *
  12.  * In addition, this file implements an nsIModule object that registers the
  13.  * nsUnknownContentTypeDialog component.
  14.  */
  15.  
  16.  
  17. /* ctor
  18.  */
  19. function nsUnknownContentTypeDialog() {
  20.     // Initialize data properties.
  21.     this.mLauncher = null;
  22.     this.mContext  = null;
  23.     this.mSourcePath = null;
  24.     this.chosenApp = null;
  25.     this.givenDefaultApp = false;
  26.     this.updateSelf = true;
  27.     this.mTitle    = "";
  28. }
  29.  
  30. nsUnknownContentTypeDialog.prototype = {
  31.     nsIMIMEInfo  : Components.interfaces.nsIMIMEInfo,
  32.  
  33.     // This "class" supports nsIHelperAppLauncherDialog, and nsISupports.
  34.     QueryInterface: function (iid) {
  35.         if (!iid.equals(Components.interfaces.nsIHelperAppLauncherDialog) &&
  36.             !iid.equals(Components.interfaces.nsISupports)) {
  37.             throw Components.results.NS_ERROR_NO_INTERFACE;
  38.         }
  39.         return this;
  40.     },
  41.  
  42.     // ---------- nsIHelperAppLauncherDialog methods ----------
  43.  
  44.     // show: Open XUL dialog using window watcher.  Since the dialog is not
  45.     //       modal, it needs to be a top level window and the way to open
  46.     //       one of those is via that route).
  47.     show: function(aLauncher, aContext, aReason)  {
  48.       this.mLauncher = aLauncher;
  49.       this.mContext  = aContext;
  50.       // Display the dialog using the Window Watcher interface.
  51.       
  52.       var ir = aContext.QueryInterface(Components.interfaces.nsIInterfaceRequestor);
  53.       var dwi = ir.getInterface(Components.interfaces.nsIDOMWindowInternal);
  54.       var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
  55.                 .getService(Components.interfaces.nsIWindowWatcher);
  56.       this.mDialog = ww.openWindow(dwi,
  57.                                    "chrome://mozapps/content/downloads/unknownContentType.xul",
  58.                                    null,
  59.                                    "chrome,centerscreen,titlebar,dialog=yes,dependent",
  60.                                    null);
  61.       // Hook this object to the dialog.
  62.       this.mDialog.dialog = this;
  63.       
  64.       // Hook up utility functions. 
  65.       this.getSpecialFolderKey = this.mDialog.getSpecialFolderKey;
  66.       
  67.       // Watch for error notifications.
  68.       this.progressListener.helperAppDlg = this;
  69.       this.mLauncher.setWebProgressListener(this.progressListener);
  70.     },
  71.  
  72.     // promptForSaveToFile:  Display file picker dialog and return selected file.
  73.     //                       This is called by the External Helper App Service
  74.     //                       after the ucth dialog calls |saveToDisk| with a null
  75.     //                       target filename (no target, therefore user must pick).
  76.     //
  77.     //                       Alternatively, if the user has selected to have all
  78.     //                       files download to a specific location, return that
  79.     //                       location and don't ask via the dialog. 
  80.     //
  81.     // Note - this function is called without a dialog, so it cannot access any part
  82.     // of the dialog XUL as other functions on this object do. 
  83.     promptForSaveToFile: function(aLauncher, aContext, aDefaultFile, aSuggestedFileExtension) {
  84.       var result = "";
  85.       
  86.       this.mLauncher = aLauncher;
  87.  
  88.       // If the user is always downloading to the same location, the default download
  89.       // folder is stored in preferences. If a value is found stored, use that 
  90.       // automatically and don't ask via a dialog. 
  91.       var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
  92.       var autodownload = prefs.getBoolPref("browser.download.useDownloadDir");
  93.       if (autodownload) {
  94.         function getSpecialFolderKey(aFolderType) 
  95.         {
  96.           if (aFolderType == "Desktop")
  97.             return "Desk";
  98.         
  99.           if (aFolderType != "Downloads")
  100.             throw "ASSERTION FAILED: folder type should be 'Desktop' or 'Downloads'";
  101.         
  102. //@line 142 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  103.           return "Pers";
  104. //@line 150 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  105.         }
  106.         
  107.         function getDownloadsFolder(aFolder)
  108.         {
  109.           var fileLocator = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties);
  110.  
  111.           var dir = fileLocator.get(getSpecialFolderKey(aFolder), Components.interfaces.nsILocalFile);
  112.           
  113.           var bundle = Components.classes["@mozilla.org/intl/stringbundle;1"].getService(Components.interfaces.nsIStringBundleService);
  114.           bundle = bundle.createBundle("chrome://mozapps/locale/downloads/unknownContentType.properties");
  115.  
  116.           var description = bundle.GetStringFromName("myDownloads");
  117.           if (aFolder != "Desktop")
  118.             dir.append(description);
  119.             
  120.           return dir;
  121.         }
  122.  
  123.         var defaultFolder = null;
  124.         switch (prefs.getIntPref("browser.download.folderList")) {
  125.         case 0:
  126.           defaultFolder = getDownloadsFolder("Desktop");
  127.           break;
  128.         case 1:
  129.           defaultFolder = getDownloadsFolder("Downloads");
  130.           break;
  131.         case 2:
  132.           defaultFolder = prefs.getComplexValue("browser.download.dir", Components.interfaces.nsILocalFile);
  133.           break;
  134.         }
  135.         
  136.         result = this.validateLeafName(defaultFolder, aDefaultFile, aSuggestedFileExtension);
  137.       }
  138.       
  139.       if (!result) {
  140.         // Use file picker to show dialog.
  141.         var nsIFilePicker = Components.interfaces.nsIFilePicker;
  142.         var picker = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
  143.  
  144.         var bundle = Components.classes["@mozilla.org/intl/stringbundle;1"].getService(Components.interfaces.nsIStringBundleService);
  145.         bundle = bundle.createBundle("chrome://mozapps/locale/downloads/unknownContentType.properties");
  146.  
  147.         var windowTitle = bundle.GetStringFromName("saveDialogTitle");
  148.         var parent = aContext.QueryInterface(Components.interfaces.nsIInterfaceRequestor).getInterface(Components.interfaces.nsIDOMWindowInternal);
  149.         picker.init(parent, windowTitle, nsIFilePicker.modeSave);
  150.         picker.defaultString = aDefaultFile;
  151.  
  152.         if (aSuggestedFileExtension) {
  153.           // aSuggestedFileExtension includes the period, so strip it
  154.           picker.defaultExtension = aSuggestedFileExtension.substring(1);
  155.         } 
  156.         else {
  157.           try {
  158.             picker.defaultExtension = this.mLauncher.MIMEInfo.primaryExtension;
  159.           } 
  160.           catch (ex) { }
  161.         }
  162.  
  163.         var wildCardExtension = "*";
  164.         if (aSuggestedFileExtension) {
  165.           wildCardExtension += aSuggestedFileExtension;
  166.           picker.appendFilter(this.mLauncher.MIMEInfo.description, wildCardExtension);
  167.         }
  168.  
  169.         picker.appendFilters( nsIFilePicker.filterAll );
  170.  
  171.         // Pull in the user's preferences and get the default download directory.
  172.         var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
  173.         try {
  174.           var startDir = prefs.getComplexValue("browser.download.dir", Components.interfaces.nsILocalFile);
  175.           if (startDir.exists()) {
  176.             picker.displayDirectory = startDir;
  177.           }
  178.         } 
  179.         catch(exception) { }
  180.  
  181.         var dlgResult = picker.show();
  182.  
  183.         if (dlgResult == nsIFilePicker.returnCancel) {
  184.           // null result means user cancelled.
  185.           return null;
  186.         }
  187.  
  188.  
  189.         // Be sure to save the directory the user chose through the Save As... 
  190.         // dialog  as the new browser.download.dir
  191.         result = picker.file;
  192.  
  193.         if (result) {
  194.           try {
  195.             // Remove the file so that it's not there when we ensure non-existence later;
  196.             // this is safe because for the file to exist, the user would have had to
  197.             // confirm that he wanted the file overwritten.
  198.             if (result.exists())
  199.               result.remove(false);
  200.           }
  201.           catch (e) { }
  202.           var newDir = result.parent;
  203.           prefs.setComplexValue("browser.download.dir", Components.interfaces.nsILocalFile, newDir);
  204.           result = this.validateLeafName(newDir, result.leafName, null);
  205.         }
  206.       }
  207.       return result;
  208.     },
  209.  
  210.     /**
  211.      * Ensures that a local folder/file combination does not already exist in
  212.      * the file system (or finds such a combination with a reasonably similar
  213.      * leaf name), creates the corresponding file, and returns it.
  214.      *
  215.      * @param   aLocalFile
  216.      *          the folder where the file resides
  217.      * @param   aLeafName
  218.      *          the string name of the file (may be empty if no name is known,
  219.      *          in which case a name will be chosen)
  220.      * @param   aFileExt
  221.      *          the extension of the file, if one is known; this will be ignored
  222.      *          if aLeafName is non-empty
  223.      * @returns nsILocalFile
  224.      *          the created file
  225.      */
  226.     validateLeafName: function (aLocalFile, aLeafName, aFileExt)
  227.     {
  228.       if (!aLocalFile || !aLocalFile.exists())
  229.         return null;
  230.  
  231.       // Remove any leading periods, since we don't want to save hidden files
  232.       // automatically.
  233.       aLeafName = aLeafName.replace(/^\.+/, "");
  234.  
  235.       if (aLeafName == "")
  236.         aLeafName = "unnamed" + (aFileExt ? "." + aFileExt : "");
  237.       aLocalFile.append(aLeafName);
  238.  
  239.       this.makeFileUnique(aLocalFile);
  240.  
  241.       if (aLocalFile.isExecutable() && !this.mLauncher.targetFile.isExecutable()) {
  242.         var f = aLocalFile.clone();
  243.         aLocalFile.leafName = aLocalFile.leafName + "." + this.mLauncher.MIMEInfo.primaryExtension; 
  244.  
  245.         f.remove(false);
  246.         this.makeFileUnique(aLocalFile);
  247.       }
  248.  
  249.       return aLocalFile;
  250.     },
  251.  
  252.     /**
  253.      * Generates and returns a uniquely-named file from aLocalFile.  If
  254.      * aLocalFile does not exist, it will be the file returned; otherwise, a
  255.      * file whose name is similar to that of aLocalFile will be returned.
  256.      */
  257.     makeFileUnique: function (aLocalFile)
  258.     {
  259.       try {
  260.         // Note - this code is identical to that in 
  261.         //   toolkit/content/contentAreaUtils.js.
  262.         // If you are updating this code, update that code too! We can't share code
  263.         // here since this is called in a js component. 
  264.         var collisionCount = 0;
  265.         while (aLocalFile.exists()) {
  266.           collisionCount++;
  267.           if (collisionCount == 1) {
  268.             // Append "(2)" before the last dot in (or at the end of) the filename
  269.             // special case .ext.gz etc files so we don't wind up with .tar(2).gz
  270.             if (aLocalFile.leafName.match(/\.[^\.]{1,3}\.(gz|bz2|Z)$/i)) {
  271.               aLocalFile.leafName = aLocalFile.leafName.replace(/\.[^\.]{1,3}\.(gz|bz2|Z)$/i, "(2)$&");
  272.             }
  273.             else {
  274.               aLocalFile.leafName = aLocalFile.leafName.replace(/(\.[^\.]*)?$/, "(2)$&");
  275.             }
  276.           }
  277.           else {
  278.             // replace the last (n) in the filename with (n+1)
  279.             aLocalFile.leafName = aLocalFile.leafName.replace(/^(.*\()\d+\)/, "$1" + (collisionCount+1) + ")");
  280.           }
  281.         }
  282.         aLocalFile.create(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0600);
  283.       }
  284.       catch (e) {
  285.         dump("*** exception in validateLeafName: " + e + "\n");
  286.         if (aLocalFile.leafName == "" || aLocalFile.isDirectory()) {
  287.           aLocalFile.append("unnamed");
  288.           if (aLocalFile.exists())
  289.             aLocalFile.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0600);
  290.         }
  291.       }
  292.     },
  293.     
  294.     // ---------- implementation methods ----------
  295.  
  296.     // Web progress listener so we can detect errors while mLauncher is
  297.     // streaming the data to a temporary file.
  298.     progressListener: {
  299.         // Implementation properties.
  300.         helperAppDlg: null,
  301.  
  302.         // nsIWebProgressListener methods.
  303.         // Look for error notifications and display alert to user.
  304.         onStatusChange: function( aWebProgress, aRequest, aStatus, aMessage ) {
  305.             if ( aStatus != Components.results.NS_OK ) {
  306.                 // Get prompt service.
  307.                 var prompter = Components.classes[ "@mozilla.org/embedcomp/prompt-service;1" ]
  308.                                    .getService( Components.interfaces.nsIPromptService );
  309.                 // Display error alert (using text supplied by back-end).
  310.                 prompter.alert( this.dialog, this.helperAppDlg.mTitle, aMessage );
  311.  
  312.                 // Close the dialog.
  313.                 this.helperAppDlg.onCancel();
  314.                 if ( this.helperAppDlg.mDialog ) {
  315.                     this.helperAppDlg.mDialog.close();
  316.                 }
  317.             }
  318.         },
  319.  
  320.         // Ignore onProgressChange, onStateChange, onLocationChange, and onSecurityChange notifications.
  321.         onProgressChange: function( aWebProgress,
  322.                                     aRequest,
  323.                                     aCurSelfProgress,
  324.                                     aMaxSelfProgress,
  325.                                     aCurTotalProgress,
  326.                                     aMaxTotalProgress ) {
  327.         },
  328.  
  329.         onProgressChange64: function( aWebProgress,
  330.                                       aRequest,
  331.                                       aCurSelfProgress,
  332.                                       aMaxSelfProgress,
  333.                                       aCurTotalProgress,
  334.                                       aMaxTotalProgress ) {
  335.         },
  336.  
  337.  
  338.  
  339.         onStateChange: function( aWebProgress, aRequest, aStateFlags, aStatus ) {
  340.         },
  341.  
  342.         onLocationChange: function( aWebProgress, aRequest, aLocation ) {
  343.         },
  344.  
  345.         onSecurityChange: function( aWebProgress, aRequest, state ) {
  346.         }
  347.     },
  348.  
  349.     // initDialog:  Fill various dialog fields with initial content.
  350.     initDialog : function() {
  351.       // Put file name in window title.
  352.       var suggestedFileName = this.mLauncher.suggestedFileName;
  353.  
  354.       // Some URIs do not implement nsIURL, so we can't just QI.
  355.       var url   = this.mLauncher.source;
  356.       var fname = "";
  357.       this.mSourcePath = url.prePath;
  358.       try {
  359.           url = url.QueryInterface( Components.interfaces.nsIURL );
  360.           // A url, use file name from it.
  361.           fname = url.fileName;
  362.           this.mSourcePath += url.directory;
  363.       } catch (ex) {
  364.           // A generic uri, use path.
  365.           fname = url.path;
  366.           this.mSourcePath += url.path;
  367.       }
  368.  
  369.       if (suggestedFileName)
  370.         fname = suggestedFileName;
  371.       
  372.       var displayName = fname.replace(/ +/g, " ");
  373.  
  374.       this.mTitle = this.dialogElement("strings").getFormattedString("title", [displayName]);
  375.       this.mDialog.document.title = this.mTitle;
  376.  
  377.       // Put content type, filename and location into intro.
  378.       this.initIntro(url, fname, displayName);
  379.  
  380.       var iconString = "moz-icon://" + fname + "?size=16&contentType=" + this.mLauncher.MIMEInfo.MIMEType;
  381.       this.dialogElement("contentTypeImage").setAttribute("src", iconString);
  382.  
  383.       // if always-save and is-executable and no-handler
  384.       // then set up simple ui
  385.       var mimeType = this.mLauncher.MIMEInfo.MIMEType;
  386.       var shouldntRememberChoice = (mimeType == "application/octet-stream" || 
  387.                                     mimeType == "application/x-msdownload" ||
  388.                                     this.mLauncher.targetFile.isExecutable());
  389.       if (shouldntRememberChoice && !this.openWithDefaultOK()) {
  390.         // hide featured choice 
  391.         this.mDialog.document.getElementById("normalBox").collapsed = true;
  392.         // show basic choice 
  393.         this.mDialog.document.getElementById("basicBox").collapsed = false;
  394.         // change button labels
  395.         this.mDialog.document.documentElement.getButton("accept").label = this.dialogElement("strings").getString("unknownAccept.label");
  396.         this.mDialog.document.documentElement.getButton("cancel").label = this.dialogElement("strings").getString("unknownCancel.label");
  397.         // hide other handler
  398.         this.mDialog.document.getElementById("openHandler").collapsed = true;
  399.         // set save as the selected option
  400.         this.dialogElement("mode").selectedItem = this.dialogElement("save");
  401.       }
  402.       else {
  403.         this.initAppAndSaveToDiskValues();
  404.  
  405.         // Initialize "always ask me" box. This should always be disabled
  406.         // and set to true for the ambiguous type application/octet-stream.
  407.         // We don't also check for application/x-msdownload here since we
  408.         // want users to be able to autodownload .exe files. 
  409.         var rememberChoice = this.dialogElement("rememberChoice");
  410.  
  411. //@line 476 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  412.         if (shouldntRememberChoice) {
  413.           rememberChoice.checked = false;
  414.           rememberChoice.disabled = true;
  415.         }
  416.         else {
  417.           rememberChoice.checked = !this.mLauncher.MIMEInfo.alwaysAskBeforeHandling;
  418.         }
  419.         this.toggleRememberChoice(rememberChoice);
  420.  
  421.         // XXXben - menulist won't init properly, hack. 
  422.         var openHandler = this.dialogElement("openHandler");
  423.         openHandler.parentNode.removeChild(openHandler);
  424.         var openHandlerBox = this.dialogElement("openHandlerBox");
  425.         openHandlerBox.appendChild(openHandler);
  426.       }
  427.  
  428.       this.mDialog.setTimeout("dialog.postShowCallback()", 0);
  429.       
  430.       this.mDialog.document.documentElement.getButton("accept").disabled = true;
  431.       const nsITimer = Components.interfaces.nsITimer;
  432.       this._timer = Components.classes["@mozilla.org/timer;1"]
  433.                               .createInstance(nsITimer);
  434.       this._timer.initWithCallback(this, 250, nsITimer.TYPE_ONE_SHOT);
  435.     },
  436.     
  437.     _timer: null,
  438.     notify: function (aTimer) {
  439.       try { // The user may have already canceled the dialog.
  440.         if (!this._blurred)
  441.           this.mDialog.document.documentElement.getButton('accept').disabled = false;
  442.       } catch (ex) {}
  443.       this._delayExpired = true;
  444.       this._timer = null; // the timer won't release us, so we have to release it
  445.     },
  446.     
  447.     postShowCallback: function () {
  448.       this.mDialog.sizeToContent();
  449.  
  450.       // Set initial focus
  451.       this.dialogElement("mode").focus();
  452.     },
  453.  
  454.     // initIntro:
  455.     initIntro: function(url, filename, displayname) {
  456.         this.dialogElement( "location" ).value = displayname;
  457.         this.dialogElement( "location" ).setAttribute("realname", filename);
  458.         this.dialogElement( "location" ).setAttribute("tooltiptext", displayname);
  459.  
  460.         // if mSourcePath is a local file, then let's use the pretty path name instead of an ugly
  461.         // url...
  462.         var pathString = this.mSourcePath;
  463.         try 
  464.         {
  465.           var fileURL = url.QueryInterface(Components.interfaces.nsIFileURL);
  466.           if (fileURL)
  467.           {
  468.             var fileObject = fileURL.file;
  469.             if (fileObject)
  470.             {
  471.               var parentObject = fileObject.parent;
  472.               if (parentObject)
  473.               {
  474.                 pathString = parentObject.path;
  475.               }
  476.             }
  477.           }
  478.         } catch(ex) {}
  479.  
  480.         if (pathString == this.mSourcePath)
  481.         {
  482.           // wasn't a fileURL
  483.           var tmpurl = url.clone(); // don't want to change the real url
  484.           try {
  485.             tmpurl.userPass = "";
  486.           } catch (ex) {}
  487.           pathString = tmpurl.prePath;
  488.         }
  489.  
  490.         // Set the location text, which is separate from the intro text so it can be cropped
  491.         var location = this.dialogElement( "source" );
  492.         location.value = pathString;
  493.         location.setAttribute("tooltiptext", this.mSourcePath);
  494.         
  495.         // Show the type of file. 
  496.         var type = this.dialogElement("type");
  497.         var mimeInfo = this.mLauncher.MIMEInfo;
  498.         
  499.         // 1. Try to use the pretty description of the type, if one is available.
  500.         var typeString = mimeInfo.description;
  501.         
  502.         if (typeString == "") {
  503.           // 2. If there is none, use the extension to identify the file, e.g. "ZIP file"
  504.           var primaryExtension = "";
  505.           try {
  506.             primaryExtension = mimeInfo.primaryExtension;
  507.           }
  508.           catch (ex) {
  509.           }
  510.           if (primaryExtension != "")
  511.             typeString = primaryExtension.toUpperCase() + " file";
  512.           // 3. If we can't even do that, just give up and show the MIME type. 
  513.           else
  514.             typeString = mimeInfo.MIMEType;
  515.         }
  516.         
  517.         type.value = typeString;
  518.     },
  519.     
  520.     _blurred: false,
  521.     _delayExpired: false, 
  522.     onBlur: function(aEvent) {
  523.       if (aEvent.target != this.mDialog.document)
  524.         return;
  525.       this._blurred = true;
  526.       this.mDialog.document.documentElement.getButton("accept").disabled = true;
  527.     },
  528.     
  529.     onFocus: function(aEvent) {
  530.       if (aEvent.target != this.mDialog.document)
  531.         return;
  532.       this._blurred = false;
  533.       if (this._delayExpired) {
  534.         var script = "document.documentElement.getButton('accept').disabled = false";
  535.         this.mDialog.setTimeout(script, 250);
  536.       }
  537.     },
  538.  
  539.     // Returns true if opening the default application makes sense.
  540.     openWithDefaultOK: function() {
  541.         var result;
  542.  
  543.         // The checking is different on Windows...
  544. //@line 609 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  545.         // Windows presents some special cases.
  546.         // We need to prevent use of "system default" when the file is
  547.         // executable (so the user doesn't launch nasty programs downloaded
  548.         // from the web), and, enable use of "system default" if it isn't
  549.         // executable (because we will prompt the user for the default app
  550.         // in that case).
  551.         
  552.         // Need to get temporary file and check for executable-ness.
  553.         var tmpFile = this.mLauncher.targetFile;
  554.         
  555.         //  Default is Ok if the file isn't executable (and vice-versa).
  556.         return !tmpFile.isExecutable();
  557. //@line 627 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  558.     },
  559.     
  560.     // Set "default" application description field.
  561.     initDefaultApp: function() {
  562.       // Use description, if we can get one.
  563.       var desc = this.mLauncher.MIMEInfo.defaultDescription;
  564.       if (desc) {
  565.         var defaultApp = this.dialogElement("strings").getFormattedString("defaultApp", [desc]);
  566.         this.dialogElement("defaultHandler").label = defaultApp;
  567.       }
  568.       else {
  569.         this.dialogElement("modeDeck").setAttribute("selectedIndex", "1");
  570.         // Hide the default handler item too, in case the user picks a 
  571.         // custom handler at a later date which triggers the menulist to show.
  572.         this.dialogElement("defaultHandler").hidden = true;
  573.       }
  574.     },
  575.  
  576.     // getPath:
  577.     getPath: function (aFile) {
  578. //@line 650 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  579.       return aFile.path;
  580. //@line 652 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  581.     },
  582.  
  583.     // initAppAndSaveToDiskValues:
  584.     initAppAndSaveToDiskValues: function() {
  585.       var modeGroup = this.dialogElement("mode");
  586.  
  587.       // We don't let users open .exe files or random binary data directly 
  588.       // from the browser at the moment because of security concerns. 
  589.       var openWithDefaultOK = this.openWithDefaultOK();
  590.       var mimeType = this.mLauncher.MIMEInfo.MIMEType;
  591.       if (this.mLauncher.targetFile.isExecutable() || (
  592.           (mimeType == "application/octet-stream" ||
  593.            mimeType == "application/x-msdownload") && 
  594.            !openWithDefaultOK)) {
  595.         this.dialogElement("open").disabled = true;
  596.         var openHandler = this.dialogElement("openHandler");
  597.         openHandler.disabled = true;
  598.         openHandler.selectedItem = null;
  599.         modeGroup.selectedItem = this.dialogElement("save");
  600.         return;
  601.       }
  602.     
  603.       // Fill in helper app info, if there is any.
  604.       this.chosenApp = this.mLauncher.MIMEInfo.preferredApplicationHandler;
  605.       // Initialize "default application" field.
  606.       this.initDefaultApp();
  607.  
  608.       var otherHandler = this.dialogElement("otherHandler");
  609.               
  610.       // Fill application name textbox.
  611.       if (this.chosenApp && this.chosenApp.path) {
  612.         otherHandler.setAttribute("path", this.getPath(this.chosenApp));
  613.         otherHandler.label = this.chosenApp.leafName;
  614.         otherHandler.hidden = false;
  615.       }
  616.  
  617.       var useDefault = this.dialogElement("useSystemDefault");
  618.       var openHandler = this.dialogElement("openHandler");
  619.       openHandler.selectedIndex = 0;
  620.  
  621.       if (this.mLauncher.MIMEInfo.preferredAction == this.nsIMIMEInfo.useSystemDefault) {
  622.         // Open (using system default).
  623.         modeGroup.selectedItem = this.dialogElement("open");
  624.       } else if (this.mLauncher.MIMEInfo.preferredAction == this.nsIMIMEInfo.useHelperApp) {
  625.         // Open with given helper app.
  626.         modeGroup.selectedItem = this.dialogElement("open");
  627.         openHandler.selectedIndex = 1;
  628.       } else {
  629.         // Save to disk.
  630.         modeGroup.selectedItem = this.dialogElement("save");
  631.       }
  632.       
  633.       // If we don't have a "default app" then disable that choice.
  634.       if (!openWithDefaultOK) {
  635.         var useDefault = this.dialogElement("defaultHandler");
  636.         var isSelected = useDefault.selected;
  637.         
  638.         // Disable that choice.
  639.         useDefault.hidden = true;
  640.         // If that's the default, then switch to "save to disk."
  641.         if (isSelected) {
  642.           openHandler.selectedIndex = 1;
  643.           modeGroup.selectedItem = this.dialogElement("save");
  644.         }
  645.       }
  646.       
  647.       // otherHandler is always disabled on Mac
  648. //@line 723 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  649.       otherHandler.nextSibling.hidden = otherHandler.nextSibling.nextSibling.hidden = false;
  650. //@line 725 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  651.       this.updateOKButton();
  652.     },
  653.  
  654.     // Returns the user-selected application
  655.     helperAppChoice: function() {
  656.       return this.chosenApp;
  657.     },
  658.     
  659.     get saveToDisk() {
  660.       return this.dialogElement("save").selected;
  661.     },
  662.     
  663.     get useOtherHandler() {
  664.       return this.dialogElement("open").selected && this.dialogElement("openHandler").selectedIndex == 1;
  665.     },
  666.     
  667.     get useSystemDefault() {
  668.       return this.dialogElement("open").selected && this.dialogElement("openHandler").selectedIndex == 0;
  669.     },
  670.     
  671.     toggleRememberChoice: function (aCheckbox) {
  672.         this.dialogElement("settingsChange").hidden = !aCheckbox.checked;
  673.         this.mDialog.sizeToContent();
  674.     },
  675.     
  676.     openHandlerCommand: function () {
  677.       var openHandler = this.dialogElement("openHandler");
  678.       if (openHandler.selectedItem.id == "choose")
  679.         this.chooseApp();
  680.       else
  681.         openHandler.setAttribute("lastSelectedItemID", openHandler.selectedItem.id);
  682.     },
  683.  
  684.     updateOKButton: function() {
  685.       var ok = false;
  686.       if (this.dialogElement("save").selected) {
  687.         // This is always OK.
  688.         ok = true;
  689.       } 
  690.       else if (this.dialogElement("open").selected) {
  691.         switch (this.dialogElement("openHandler").selectedIndex) {
  692.         case 0:
  693.           // No app need be specified in this case.
  694.           ok = true;
  695.           break;
  696.         case 1:
  697.           // only enable the OK button if we have a default app to use or if 
  698.           // the user chose an app....
  699.           ok = this.chosenApp || /\S/.test(this.dialogElement("otherHandler").getAttribute("path")); 
  700.         break;
  701.         }
  702.       }
  703.  
  704.       // Enable Ok button if ok to press.
  705.       this.mDialog.document.documentElement.getButton("accept").disabled = !ok;
  706.     },
  707.     
  708.     // Returns true iff the user-specified helper app has been modified.
  709.     appChanged: function() {
  710.       return this.helperAppChoice() != this.mLauncher.MIMEInfo.preferredApplicationHandler;
  711.     },
  712.  
  713.     updateMIMEInfo: function() {
  714.       var needUpdate = false;
  715.       // If current selection differs from what's in the mime info object,
  716.       // then we need to update.
  717.       if (this.saveToDisk) {
  718.         needUpdate = this.mLauncher.MIMEInfo.preferredAction != this.nsIMIMEInfo.saveToDisk;
  719.         if (needUpdate)
  720.           this.mLauncher.MIMEInfo.preferredAction = this.nsIMIMEInfo.saveToDisk;
  721.       } 
  722.       else if (this.useSystemDefault) {
  723.         needUpdate = this.mLauncher.MIMEInfo.preferredAction != this.nsIMIMEInfo.useSystemDefault;
  724.         if (needUpdate)
  725.           this.mLauncher.MIMEInfo.preferredAction = this.nsIMIMEInfo.useSystemDefault;
  726.       } 
  727.       else {
  728.         // For "open with", we need to check both preferred action and whether the user chose
  729.         // a new app.
  730.         needUpdate = this.mLauncher.MIMEInfo.preferredAction != this.nsIMIMEInfo.useHelperApp || this.appChanged();
  731.         if (needUpdate) {
  732.           this.mLauncher.MIMEInfo.preferredAction = this.nsIMIMEInfo.useHelperApp;
  733.           // App may have changed - Update application and description
  734.           var app = this.helperAppChoice();
  735.           this.mLauncher.MIMEInfo.preferredApplicationHandler = app;
  736.           this.mLauncher.MIMEInfo.applicationDescription = "";
  737.         }
  738.       }
  739.       // We will also need to update if the "always ask" flag has changed.
  740.       needUpdate = needUpdate || this.mLauncher.MIMEInfo.alwaysAskBeforeHandling != (!this.dialogElement("rememberChoice").checked);
  741.  
  742.       // One last special case: If the input "always ask" flag was false, then we always
  743.       // update.  In that case we are displaying the helper app dialog for the first
  744.       // time for this mime type and we need to store the user's action in the mimeTypes.rdf
  745.       // data source (whether that action has changed or not; if it didn't change, then we need
  746.       // to store the "always ask" flag so the helper app dialog will or won't display
  747.       // next time, per the user's selection).
  748.       needUpdate = needUpdate || !this.mLauncher.MIMEInfo.alwaysAskBeforeHandling;
  749.  
  750.       // Make sure mime info has updated setting for the "always ask" flag.
  751.       this.mLauncher.MIMEInfo.alwaysAskBeforeHandling = !this.dialogElement("rememberChoice").checked;
  752.  
  753.       return needUpdate;        
  754.     },
  755.     
  756.     // See if the user changed things, and if so, update the
  757.     // mimeTypes.rdf entry for this mime type.
  758.     updateHelperAppPref: function() {
  759.       var ha = new this.mDialog.HelperApps();
  760.       ha.updateTypeInfo(this.mLauncher.MIMEInfo);
  761.       ha.destroy();
  762.     },
  763.     
  764.     // onOK:
  765.     onOK: function() {
  766.       // Verify typed app path, if necessary.
  767.       if (this.useOtherHandler) {
  768.         var helperApp = this.helperAppChoice();
  769.         if (!helperApp || !helperApp.exists()) {
  770.           // Show alert and try again.        
  771.           var bundle = this.dialogElement("strings");                    
  772.           var msg = bundle.getFormattedString("badApp", [this.dialogElement("otherHandler").path]);
  773.           var svc = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
  774.           svc.alert(this.mDialog, bundle.getString("badApp.title"), msg);
  775.  
  776.           // Disable the OK button.
  777.           this.mDialog.document.documentElement.getButton("accept").disabled = true;
  778.           this.dialogElement("mode").focus();          
  779.  
  780.           // Clear chosen application.
  781.           this.chosenApp = null;
  782.  
  783.           // Leave dialog up.
  784.           return false;
  785.         }
  786.       }
  787.         
  788.       // Remove our web progress listener (a progress dialog will be
  789.       // taking over).
  790.       this.mLauncher.setWebProgressListener(null);
  791.       
  792.       // saveToDisk and launchWithApplication can return errors in 
  793.       // certain circumstances (e.g. The user clicks cancel in the
  794.       // "Save to Disk" dialog. In those cases, we don't want to
  795.       // update the helper application preferences in the RDF file.
  796.       try {
  797.         var needUpdate = this.updateMIMEInfo();
  798.         
  799.         if (this.dialogElement("save").selected) {
  800.           // If we're using a default download location, create a path
  801.           // for the file to be saved to to pass to |saveToDisk| - otherwise
  802.           // we must ask the user to pick a save name.
  803.  
  804. //@line 892 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  805.           this.mLauncher.saveToDisk(null, false);
  806.         }
  807.         else
  808.           this.mLauncher.launchWithApplication(null, false);
  809.  
  810.         // Update user pref for this mime type (if necessary). We do not
  811.         // store anything in the mime type preferences for the ambiguous
  812.         // type application/octet-stream. We do NOT do this for 
  813.         // application/x-msdownload since we want users to be able to 
  814.         // autodownload these to disk. 
  815.         if (needUpdate && this.mLauncher.MIMEInfo.MIMEType != "application/octet-stream")
  816.           this.updateHelperAppPref();
  817.       } catch(e) { }
  818.  
  819.       // Unhook dialog from this object.
  820.       this.mDialog.dialog = null;
  821.  
  822.       // Close up dialog by returning true.
  823.       return true;
  824.     },
  825.  
  826.     // onCancel:
  827.     onCancel: function() {
  828.       // Remove our web progress listener.
  829.       this.mLauncher.setWebProgressListener(null);
  830.  
  831.       // Cancel app launcher.
  832.       try {
  833.         const NS_BINDING_ABORTED = 0x804b0002;
  834.         this.mLauncher.cancel(NS_BINDING_ABORTED);
  835.       } catch(exception) {
  836.       }
  837.  
  838.       // Unhook dialog from this object.
  839.       this.mDialog.dialog = null;
  840.  
  841.       // Close up dialog by returning true.
  842.       return true;
  843.     },
  844.  
  845.     // dialogElement:  Convenience. 
  846.     dialogElement: function(id) {
  847.       return this.mDialog.document.getElementById(id);
  848.     },
  849.  
  850.     // chooseApp:  Open file picker and prompt user for application.
  851.     chooseApp: function() {
  852.       var nsIFilePicker = Components.interfaces.nsIFilePicker;
  853.       var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
  854.       fp.init(this.mDialog,
  855.               this.dialogElement("strings").getString("chooseAppFilePickerTitle"),
  856.               nsIFilePicker.modeOpen);
  857.  
  858.       fp.appendFilters(nsIFilePicker.filterApps);
  859.  
  860.       if (fp.show() == nsIFilePicker.returnOK && fp.file) {
  861.         // Show the "handler" menulist since we have a (user-specified) 
  862.         // application now.
  863.         this.dialogElement("modeDeck").setAttribute("selectedIndex", "0");
  864.         
  865.         // Remember the file they chose to run.
  866.         this.chosenApp = fp.file;
  867.         // Update dialog.
  868.         var otherHandler = this.dialogElement("otherHandler");
  869.         otherHandler.removeAttribute("hidden");
  870.         otherHandler.setAttribute("path", this.getPath(this.chosenApp));
  871.         otherHandler.label = this.chosenApp.leafName;
  872.         this.dialogElement("openHandler").selectedIndex = 1;
  873.         this.dialogElement("openHandler").setAttribute("lastSelectedItemID", "otherHandler");
  874.         
  875.         this.dialogElement("mode").selectedItem = this.dialogElement("open");
  876.       }
  877.       else {
  878.         var openHandler = this.dialogElement("openHandler");
  879.         var lastSelectedID = openHandler.getAttribute("lastSelectedItemID");
  880.         if (!lastSelectedID)
  881.           lastSelectedID = "defaultHandler";
  882.         openHandler.selectedItem = this.dialogElement(lastSelectedID);
  883.       }
  884.     },
  885.  
  886.     // Turn this on to get debugging messages.
  887.     debug: false,
  888.  
  889.     // Dump text (if debug is on).
  890.     dump: function( text ) {
  891.         if ( this.debug ) {
  892.             dump( text ); 
  893.         }
  894.     },
  895.  
  896.     // dumpInfo:
  897.     doDebug: function() {
  898.         const nsIProgressDialog = Components.interfaces.nsIProgressDialog;
  899.         // Open new progress dialog.
  900.         var progress = Components.classes[ "@mozilla.org/progressdialog;1" ]
  901.                          .createInstance( nsIProgressDialog );
  902.         // Show it.
  903.         progress.open( this.mDialog );
  904.     },
  905.  
  906.     // dumpObj:
  907.     dumpObj: function( spec ) {
  908.          var val = "<undefined>";
  909.          try {
  910.              val = eval( "this."+spec ).toString();
  911.          } catch( exception ) {
  912.          }
  913.          this.dump( spec + "=" + val + "\n" );
  914.     },
  915.  
  916.     // dumpObjectProperties
  917.     dumpObjectProperties: function( desc, obj ) {
  918.          for( prop in obj ) {
  919.              this.dump( desc + "." + prop + "=" );
  920.              var val = "<undefined>";
  921.              try {
  922.                  val = obj[ prop ];
  923.              } catch ( exception ) {
  924.              }
  925.              this.dump( val + "\n" );
  926.          }
  927.     }
  928. }
  929.  
  930. // This Component's module implementation.  All the code below is used to get this
  931. // component registered and accessible via XPCOM.
  932. var module = {
  933.     firstTime: true,
  934.  
  935.     // registerSelf: Register this component.
  936.     registerSelf: function (compMgr, fileSpec, location, type) {
  937.         if (this.firstTime) {
  938.             this.firstTime = false;
  939.             throw Components.results.NS_ERROR_FACTORY_REGISTER_AGAIN;
  940.         }
  941.         compMgr = compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  942.  
  943.         compMgr.registerFactoryLocation( this.cid,
  944.                                          "Unknown Content Type Dialog",
  945.                                          this.contractId,
  946.                                          fileSpec,
  947.                                          location,
  948.                                          type );
  949.     },
  950.  
  951.     // getClassObject: Return this component's factory object.
  952.     getClassObject: function (compMgr, cid, iid) {
  953.         if (!cid.equals(this.cid)) {
  954.             throw Components.results.NS_ERROR_NO_INTERFACE;
  955.         }
  956.  
  957.         if (!iid.equals(Components.interfaces.nsIFactory)) {
  958.             throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  959.         }
  960.  
  961.         return this.factory;
  962.     },
  963.  
  964.     /* CID for this class */
  965.     cid: Components.ID("{F68578EB-6EC2-4169-AE19-8C6243F0ABE1}"),
  966.  
  967.     /* Contract ID for this class */
  968.     contractId: "@mozilla.org/helperapplauncherdialog;1",
  969.  
  970.     /* factory object */
  971.     factory: {
  972.         // createInstance: Return a new nsProgressDialog object.
  973.         createInstance: function (outer, iid) {
  974.             if (outer != null)
  975.                 throw Components.results.NS_ERROR_NO_AGGREGATION;
  976.  
  977.             return (new nsUnknownContentTypeDialog()).QueryInterface(iid);
  978.         }
  979.     },
  980.  
  981.     // canUnload: n/a (returns true)
  982.     canUnload: function(compMgr) {
  983.         return true;
  984.     }
  985. };
  986.  
  987. // NSGetModule: Return the nsIModule object.
  988. function NSGetModule(compMgr, fileSpec) {
  989.     return module;
  990. }
  991.